import { NextRequest, NextResponse } from 'next/server';
import { getUserManagement } from '@/lib/user-management';
import { cookies } from 'next/headers';

// 验证管理员权限的中间件函数
async function verifyAdminPermission() {
  const cookieStore = await cookies();
  const sessionToken = cookieStore.get('session_token')?.value;

  if (!sessionToken) {
    return { error: '未登录', status: 401 };
  }

  const userMgmt = getUserManagement();
  const user = userMgmt.validateSession(sessionToken);

  if (!user) {
    return { error: '会话已过期', status: 401 };
  }

  const permissions = userMgmt.parseRolePermissions(user.role_permissions);
  if (!permissions.canManageUsers) {
    return { error: '权限不足', status: 403 };
  }

  return { user, userMgmt };
}

// GET /api/admin/users - 获取所有用户
export async function GET(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission();
    if ('error' in authResult) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status });
    }

    const { userMgmt } = authResult;
    const users = userMgmt.getAllUsers();

    // 移除密码字段
    const safeUsers = users.map(user => {
      const { ...safeUser } = user;
      return safeUser;
    });

    return NextResponse.json({
      success: true,
      data: safeUsers
    });

  } catch (error) {
    console.error('获取用户列表失败:', error);
    return NextResponse.json({
      success: false,
      error: '获取用户列表失败'
    }, { status: 500 });
  }
}

// POST /api/admin/users - 创建新用户
export async function POST(request: NextRequest) {
  try {
    const authResult = await verifyAdminPermission();
    if ('error' in authResult) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status });
    }

    const { userMgmt } = authResult;
    const userData = await request.json();

    // 验证必填字段
    const { username, password, email, full_name, role_id } = userData;
    if (!username || !password || !email || !full_name || !role_id) {
      return NextResponse.json({
        success: false,
        error: '缺少必填字段'
      }, { status: 400 });
    }

    // 检查用户名是否已存在
    const existingUsers = userMgmt.getAllUsers();
    if (existingUsers.some(user => user.username === username)) {
      return NextResponse.json({
        success: false,
        error: '用户名已存在'
      }, { status: 400 });
    }

    // 检查邮箱是否已存在
    if (existingUsers.some(user => user.email === email)) {
      return NextResponse.json({
        success: false,
        error: '邮箱已存在'
      }, { status: 400 });
    }

    const userId = await userMgmt.createUser({
      username,
      password,
      email,
      full_name,
      role_id: parseInt(role_id),
      is_active: userData.is_active !== false
    });

    return NextResponse.json({
      success: true,
      data: { id: userId }
    });

  } catch (error) {
    console.error('创建用户失败:', error);
    return NextResponse.json({
      success: false,
      error: '创建用户失败'
    }, { status: 500 });
  }
}
